
package rendi456.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class Client
{
	public static final String IP = "127.0.0.1";
	private Socket s = null;
	private ClientChannel list = null;
	private String name = null;
	private ObjectOutputStream out = null;
	private ObjectInputStream in = null;

	public Client(String name) throws IOException
	{
		this.name = name;
		this.list = new ClientChannel();

	}

	public boolean connect() throws IOException
	{
		Thread t = null;
		boolean answer = false;

		System.out.println(this + " connecting");
		this.s = new Socket(IP, Test.PORT);

		this.out = new ObjectOutputStream(this.s.getOutputStream());

		this.in = new ObjectInputStream(this.s.getInputStream());

		System.out.println(this + " Sending name");
		this.out.writeUTF(this.name);
		this.out.flush();

		t = new Thread(this.list);
		t.start();

		return answer;
	}

	public void feed(Object o)
	{
		try
		{
			System.out.println(this + " feed \"" + o + "\"");
			out.writeObject(o);
			this.out.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public String toString()
	{
		return "#CLIENT:" + this.name + Test.getThreadName() + "#";
	}

	private class ClientChannel implements Runnable, Channel
	{
		@Override
		public void listen1()
		{
			Object o = null;
			System.out.println(this + " connected to server");
			try
			{
				do
				{
					System.out.println(this + " waiting for input");
					o = Client.this.in.readObject();
					System.out.println(this + " \"" + o + "\" read");
				}
				while (true);
			}
			catch (IOException e)
			{
			}
			catch (ClassNotFoundException e)
			{
			}
		}

		@Override
		public void run()
		{
			boolean answer = false;

			try
			{
				System.out.println(this + " waiting for answer from server");
				answer = Client.this.in.readBoolean();
				System.out.println(this + " answer is " + answer);
				if (answer)
				{
					this.listen1();
				}
			}
			catch (IOException e)
			{
			}
		}

		@Override
		public String toString()
		{
			return "#CLIENT_LIST:" + Client.this.name + Test.getThreadName()
					+ "#";
		}

	}

}
